import * as React from 'react'
import {
  Col,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Button,
  Form,
  Divider,
  message
} from 'antd'
import axios from '@/utils/axios'
import api from '@/api'
import moment from 'moment'
import './styles.less'

const FormItem = Form.Item
const Option = Select.Option
interface Props {
  id: '';
  onSuccess: Function;
  onClose: Function;
}
export class BaseDetail extends React.PureComponent<Props> {
  state = {
    loading: false,
    editing: false,
    detailData: {}
  }
  apiDetail = api.order.detail
  apiUpdate = api.order.update
  displayRows = [
    { key: 'order_code', label: '货物编号（唯一）', disabled: true }
  ]
  // 转换带select选项的options数据
  mapUpdateData(data) {}
  fetchOptions() {}

  /* ------------------------------------------------------- */
  handleCancel() {
    this.setState({
      editing: false
    })
  }
  handleEdit() {
    this.setState({
      editing: true
    })
    // this.fetchReceiptorOptions(this.state.detailData.customer_id)
  }
  handleCommonSelectOnChange(v, option) {
    this.props.form.setFieldsValue({
      ...option.props.data
    })
  }
  handleConfirm() {
    if (this.state.editing) {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (err) {
          console.error(err)
          return
        }
        const reqData = JSON.parse(JSON.stringify(values))
        this.mapUpdateData(reqData)

        axios.post(this.apiUpdate, reqData).then(res => {
          if (res.data.code === 200) {
            this.props.form.resetFields()
            this.setState({
              editing: false
            })
            this.props.onSuccess()
          } else {
            message.error(res.data.msg)
          }
        })
      })
    } else {
      this.props.onClose()
    }
  }
  mapDetailReqData(id) {
    return { id: id || this.props.id }
  }
  fetchData(id) {
    this.setState({
      loading: true,
      editing: false
    })
    this.fetchOptions()
    const reqData = this.mapDetailReqData(id)
    axios
      .post(this.apiDetail, reqData)
      .then(res => {
        if (res.data && res.data.code === 200) {
          this.setState({
            loading: false
          })
          const fields = {}
          this.displayRows.forEach(item => {
            let v = res.data.details[item.key]
            if (item.type == 'date') {
              v = v ? moment(v) : undefined
            }
            fields[item.key] = v
          })
          console.log(fields)
          this.setState({
            detailData: fields
          })
        }
      })
  }
  componentWillReceiveProps(newProps) {
    if (this.props.id !== newProps.id) {
      this.fetchData(newProps.id)
    }
  }
  componentDidUpdate(preProps, preState) {
    if (!preState.editing && this.state.editing) {
      this.props.form.setFieldsValue(this.state.detailData)
    }
  }
  componentDidMount() {
    this.fetchData()
  }
  renderInput(conf) {
    switch (conf.type) {
      case 'number':
        return <InputNumber {...conf.attr} />
      case 'select':
        const options = conf.options
        return (
          <Select
            disabled={conf.disabled}
            onChange={conf.onChange || this.commonSelectOnChange}
            {...conf.attr}
          >
            {options.map((option, index) => {
              return (
                <Option key={index} data={option} value={index}>
                  {option[conf.key]}
                </Option>
              )
            })}
          </Select>
        )
      case 'date':
        return <DatePicker {...conf.attr} />
      case 'textArea':
        return <Input.TextArea {...conf.attr}/> 
      case 'divider':
        return <Divider {...conf.attr}>{conf.label}</Divider>
      default:
        return <Input {...conf.attr} />
    }
  }
  renderDetailItem(conf) {
    const v = this.state.detailData[conf.key]
    switch (conf.type) {
      case 'select':
        if (v === +v) {
          const option = conf.options[v]
          return conf.map ? conf.map(v) : (option ? option[conf.key] : '')
        } else {
          return v
        }
      case 'date':
        return v ? moment(v).format('YYYY-MM-DD') : ''
      case 'divider':
        return <Divider {...conf.attr}>{conf.label}</Divider>
      default:
        return v
    }
  }
  renderFooter() {
    return this.state.editing ? (
      <div className="detail-footer">
        <Button type="primary" onClick={() => this.handleConfirm()}>
          提交
        </Button>
        <Button onClick={() => this.handleCancel()}>取消</Button>
      </div>
    ) : (
      <div className="detail-footer">
        <Button type="primary" onClick={() => this.handleConfirm()}>
          关闭
        </Button>
        <Button onClick={() => this.handleEdit()}>编辑</Button>
      </div>
    )
  }
  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <div className="base-detail">
        <Form className="detail-content">
          {this.displayRows.map((item, index) => {
            return (
              <Col {...item.colAttr} offset={item.offset || 0} span={item.span || 12} key={index}>
                <FormItem
                  // labelCol={item.labelCol || { offset: 1, span: 6 }}
                  // wrapperCol={item.wrapperCol || { span: 11 }}
                  {...item.formAttr}
                  label={item.type !== 'divider' ? item.label : ''}
                  key={item.key}
                >
                  {' '}
                  {this.state.editing
                    ? getFieldDecorator(item.key, { rules: item.rules })(
                        this.renderInput(item)
                      )
                    : this.renderDetailItem(item)}
                </FormItem>
              </Col>
            )
          })}
        </Form>
        {this.renderFooter()}
      </div>
    )
  }
}
export default Form.create()(BaseDetail)
